package com.project.common.resolvers;

import com.alibaba.fastjson.JSONObject;
import com.project.common.enums.LoginEnum;
import com.project.common.model.UserInfo;
import com.project.common.utils.ThreadLocalBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户信息自定义参数解析类
 */
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType() == UserInfo.class;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
       String token = ThreadLocalBuilder.getToken();
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
       if (StringUtils.isNotEmpty(token)){
           Object userInfo_json = request.getSession().getAttribute(LoginEnum.LOGIN_SESSION_VALUE.Value() + token);
           if (null != userInfo_json){
               UserInfo userInfo = JSONObject.parseObject(userInfo_json.toString(), UserInfo.class);
               return userInfo;
           }
       }
        return null;
    }
}
